import { NameSpace } from 'utils';
import exceed from 'utils/apimap';

const ns = NameSpace('group');
export const RECEIVE_DATA = ns('RECEIVE_DATA');
export const RECEIVE_PROJECTINFO = ns('RECEIVE_PROJECTINFO');
export const RESET_DATA = ns('RESET_DATA');
export const RESET_ISPROJECTINFOFETCHED = ns('RESET_ISPROJECTINFOFETCHED');
export const SET_IMPORT_STATUS = ns('SET_IMPORT_STATUS');
export const UPDATE_DATA = ns('UPDATE_DATA');

export function getPublicData() {
  return (dispatch) => {
    exceed
      .forceFetch({
        api: 'demo.get',
      })
      .then((result) => {
        dispatch({
          type: RECEIVE_DATA,
          data: result,
        });
      });
  };
}

export function resetData() {
  return (dispatch) => {
    dispatch({
      type: RESET_DATA,
    });
  };
}

export function updateData(data) {
  return (dispatch) => {
    dispatch({
      type: UPDATE_DATA,
      data,
    });
  };
}

export function getGroupInfo() {
  return (dispatch, getState) => {
    const { pathResource } = getState().root.pageInfo;
    const fetchParams = {
      api: 'group.detail',
      params: {
        id: pathResource.id,
        contain_sub_projects: false,
      },
    };
    updateData({
      isLoadingGroupInfo: true,
    })(dispatch);
    const promise = new Promise((resolve, reject) => {
      exceed
        .fetch(fetchParams)
        .then((result) => {
          resolve(result);
        })
        .fail((err) => {
          reject(err);
        });
    });
    promise
      .then((result) => {
        updateData({
          groupInfo: result,
          isLoadingGroupInfo: false,
        })(dispatch);
      })
      .catch((err) => {
        updateData({
          isLoadingGroupInfo: false,
        })(dispatch);
        console.error(err);
      });
  };
}
